# -*- coding: utf-8 -*-
__author__ = "Ypf"
_date_ = "2019/6/25-17:00"

'''
销售经理相关数据报表模块
'''

from common.utils import level_charge, format_float
from crm_data_report.config import crm_cal_fields, khul_xishu, xiaoshoujingli_dic, xsjl_jl_dic, xsjl_list
from crm_data_report.cm_db import AccountMgr, filter_sb
from crm_data_report.cm_process import convert_bili, cm_main
from crm_data_report.sm_db import SalesManager

def  sm_main(begin_day,end_day):
    #时间的调节准备
    year = begin_day.split("-")[0]
    month = begin_day.split("-")[1]
    begin_time = f"{begin_day} 00:00:00"
    end_time = f"{end_day} 23:59:59"
    mohu_time = f"{year}-{month[-1]}%" if month.startswith('0') else f"{year}-{month}%"
    cal_type = crm_cal_fields['sales_rp']

    id_sql = cal_type.get('id_sname')
    name_dic = AccountMgr.get_id_name(id_sql)

    # 所有销售经理对比表

    # 输入时间生成统计绩效字典
    sales_score_sql = cal_type.get('tjjx_score') % (begin_time, end_time)
    tjjx_dict = SalesManager.get_tjjx(sales_score_sql, name_dic)

    for key in tjjx_dict:
        try:
            tjjx_dict[key] = [format_float(sum(tjjx_dict[key]) / (len(xiaoshoujingli_dic[key]) - 1))]
        except TypeError as e :
            print(e)
    dic_tjjx = convert_bili(tjjx_dict, 40)
        # 算出所对应的比例值




    # 输入时间生成报告积分字典
    sales_score_sql = cal_type.get('bgjf_score') % (begin_time, end_time)
    bgjf_dict = SalesManager.get_bgjf(sales_score_sql, name_dic)




    # 算出所对应的比例值
    dic_bgjf = convert_bili(bgjf_dict, 10)

    # 生成统计积分
    dic_tjjf_first = {}
    dic_kh = cm_main(begin_day, end_day)
    dic_kh=filter_sb(dic_kh,xsjl_list)
    for key in dic_kh:
        dic_tjjf_first[key] = format_float( dic_kh[key][5] / khul_xishu[key])
    dic_tjjf={}
    for key in  xiaoshoujingli_dic:
        tjjf=0
        for i in xiaoshoujingli_dic[key]:
            if i in dic_tjjf_first.keys():
                tjjf+=dic_tjjf_first[i]
        dic_tjjf[key]=[format_float(tjjf)/len(xiaoshoujingli_dic[key])]
    print('################%s' % (dic_tjjf))
    dic_tjjf=convert_bili(dic_tjjf, 50)
#     合并三个字典
    for key in dic_tjjf:
        dic_tjjf[key].extend( key for key in  dic_tjjx[key])
        dic_tjjf[key].extend(key for key in dic_bgjf[key])
        dic_tjjf[key].extend(key for key in xsjl_jl_dic[key])
        dic_tjjf[key].append(format_float(sum([dic_tjjf[key][1],dic_tjjf[key][3],dic_tjjf[key][5],dic_tjjf[key][6],dic_tjjf[key][7]])))
        dic_tjjf[key].append(format_float(dic_tjjf[key][8]/sum([dic_tjjf[key][6],dic_tjjf[key][7],100])/0.25))
        level=level_charge(dic_tjjf[key][9])
        dic_tjjf[key].extend(key for key in  level)
        dic_tjjf[key]=tuple(dic_tjjf[key])
    db_insert_sql=cal_type.get('xsjl_insert_sql')
    print("end%s"%(dic_tjjf))
    SalesManager.sale_xsjl_statics(begin_time, end_time,dic_tjjf,db_insert_sql)



